﻿using BZ.Core.Frm;
using NDK.Motion.MachineManager;
using  NDK.Motion.MachineResources;
using  NDK.Motion.Properties;
using  System;
using System.Collections.Generic;
using  System.ComponentModel;
using  System.Threading;
using  System.Windows.Forms;

namespace  NDK.Motion.Frm
{
    public partial class Frm_Cylinder : Form
    {
        private static log4net.ILog traceLogger = log4net.LogManager.GetLogger("Frm_Cylinder");

        /// <summary>
        /// 是否实时监控Cylinder状态
        /// </summary>
        public bool isMonitoring = false;
        /// <summary>
        /// 窗体关闭状态
        /// </summary>
        public bool isFrmClosed = false;
        private Frm_Cylinder()
        {
            InitializeComponent();
        }
        private static Frm_Cylinder _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Cylinder Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new Frm_Cylinder();
                        }
                    }
                }
                return _instance;
            }
        }
        private void Frm_Cylinder_Load(object sender, EventArgs e)
        {
            dgv_Cylinder.DataSource = new BindingList<ICylinder>(MachineDataManager.Instance.CylinderList);
            isFrmClosed = false;
            backgroundWorker1.RunWorkerAsync();
        }

        private void btn_FindCylinder_BtnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tb_Name.Text.Trim()))
            {
                dgv_Cylinder.DataSource = new BindingList<ICylinder>(MachineDataManager.Instance.CylinderList.FindAll(i => i.Name.Contains(tb_Name.Text.Trim())));
                return;
            }
            if (string.IsNullOrEmpty(tb_Name.Text.Trim()))
            {
                dgv_Cylinder.DataSource = new BindingList<ICylinder>(MachineDataManager.Instance.CylinderList);
            }
        }

        private void ckb_Monitoring_CheckedChanged(object sender, EventArgs e)
        {
            if (ckb_Monitoring.CheckState == CheckState.Checked)
            {
                isMonitoring = true;
            }
            else
            {
                isMonitoring = false;
            }
        }
        /// <summary>
        /// 实时监控DI状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isFrmClosed == false)
            {
                if (isMonitoring == true)
                {
                    for (int rowIndex = 0; rowIndex < dgv_Cylinder.Rows.Count; rowIndex++)
                    {
                        try
                        {
                            dgv_Cylinder.Invoke(new Action(() =>
                            {
                                //DataGridView处于编辑状态时，不检查状态
                                if (!dgv_Cylinder.Rows[rowIndex].IsNewRow)
                                {
                                    if (!dgv_Cylinder.Rows[rowIndex].Cells["cName"].IsInEditMode)
                                    {
                                        //获取当前行的Cylinder
                                        string name = dgv_Cylinder.Rows[rowIndex].Cells["cName"].Value.ToString();
                                        ICylinder cylinder = MachineDataManager.Instance.CylinderList.Find(c => c.Name == name);
                                        //得到气缸的Work/Home状态，更新界面状态
                                        bool? isHomed = cylinder.isHomed();
                                        bool? isWorked = cylinder.isWorked();
                                        //dgv_Cylinder.Rows[rowIndex].Cells["cHomed"].Value = (isHomed == true) ? Resources.LightOn : Resources.LightOff;
                                        //dgv_Cylinder.Rows[rowIndex].Cells["cWorked"].Value = (isHomed == true) ? Resources.LightOn : Resources.LightOff;

                                        dgv_Cylinder.Rows[rowIndex].Cells["cHomed"].Value = (isHomed == true) ? true : false;
                                        dgv_Cylinder.Rows[rowIndex].Cells["cWorked"].Value = (isWorked == true) ? true : false;
                                    }
                                }
                            }));
                        }
                        catch (Exception ex)
                        {
                            traceLogger.Error(ex.StackTrace);
                        }
                        Application.DoEvents();
                    }
                }
                Thread.Sleep(50);
            }
        }

        private void dgv_Cylinder_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (isMonitoring == true)
            {
                try
                {
                    //DataGridView处于编辑状态时，不检查状态
                    int rowIndex = dgv_Cylinder.CurrentRow.Index;
                    if (dgv_Cylinder.Rows[rowIndex].IsNewRow) return;
                    if (dgv_Cylinder.CurrentCell.OwningColumn.Name != "cSetDO") return;
                    //获取点击状态，checkbox=true 设置气缸Work，否则设置Home
                    dgv_Cylinder.CurrentCell = null;
                    string strIsRun = dgv_Cylinder.Rows[rowIndex].Cells["cSetDO"].Value.ToString();
                    if (strIsRun == string.Empty) return;
                    bool isRun = bool.Parse(strIsRun);
                    //获取当前行的Cylinder
                    string name = dgv_Cylinder.Rows[rowIndex].Cells["cName"].Value.ToString();

                    ICylinder cylinder = MachineDataManager.Instance.CylinderList.Find(c => c.Name == name);
                    if (isRun)
                    {
                        cylinder.Work();
                    }
                    else
                    {
                        cylinder.Home();
                    }
                    dgv_Cylinder.CurrentCell = null;
                }
                catch (Exception ex)
                {
                    traceLogger.Error(ex.StackTrace);
                }
            }
        }

        private void btn_Add_BtnClick(object sender, EventArgs e)
        {
            Frm_AddCylinder addFrm = new Frm_AddCylinder();
            if (addFrm.ShowDialog(this) == DialogResult.OK)
                dgv_Cylinder.DataSource = MachineDataManager.Instance.CylinderList;
        }

        private void Frm_Cylinder_FormClosing(object sender, FormClosingEventArgs e)
        {
            isFrmClosed = true;
        }

        private void btn_Delete_BtnClick(object sender, EventArgs e)
        {
            var rows = dgv_Cylinder.CurrentRow.Index;
            if (rows >= 0)
            {
                Dlg_Confirm dlg_Confirm = new Dlg_Confirm("提示", $"确定删除{string.Join(",", MachineDataManager.Instance.CylinderList[rows].Name)}?");
                DialogResult dialogResult = dlg_Confirm.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    MachineDataManager.Instance.CylinderList.RemoveAt(rows);
                    dgv_Cylinder.DataSource = new BindingList<ICylinder>(MachineDataManager.Instance.CylinderList);
                }
            }
        }
    }
}
